<?php

namespace App\Http\Controllers\Api;

use App\Http\Controllers\Controller;
use App\Model\UserModel as User;
use App\Model\UserAuthModel as UserAuth;

use Illuminate\Support\Facades\DB;


class AuthController extends Controller
{
	//实名认证首页
	public function index(){
		$user = User::where('id',request()->uid)->first();
		if(!$user){
			return ['code'=>0,'msg'=>13];
		}
		$data['remark'] = '';
		$auth = UserAuth::where('uid',$user['id'])->first();
		if($auth){
			$data['remark'] = $auth->remark;
		}
		$data['is_auth'] = $user->is_auth;

		return ['code'=>1,'msg'=>'返回数据','data'=>$data];
	}

	//验证图片
	public function check(){
		$auth_name = "/^[\x{4e00}-\x{9fa5}]{2,6}$/u";
		$auth_idcard = "/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/";

		//姓名
		if(!request()->name){
			return ['code'=>0,'msg'=>retStrInfo(46)];
		}

		if(!request()->idcard){
			return ['code'=>0,'msg'=>retStrInfo(47)];
		}
		if (!preg_match($auth_name, request()->name)) {
			return ['code' => 0, 'msg' => retStrInfo(50)];
		}
		if (!preg_match($auth_idcard, request()->idcard)) {
			return ['code' => 0, 'msg' => retStrInfo(51)];
		}


		//身份证正面
		$idcard_headz = upload('idcard_headz','auth',1);
		if($idcard_headz['code'] == 0){
			return ['code'=>0,'msg'=>$idcard_headz['msg']];
		}
		//身份证反面
		$idcard_headf = upload('idcard_headf','auth',2);
		if($idcard_headf['code'] == 0){
			return ['code'=>0,'msg'=>$idcard_headf['msg']];
		}
		//手持身份证正面
		$idcard_handz = upload('idcard_handz','auth',3);
		if($idcard_handz['code'] == 0){
			return ['code'=>0,'msg'=>$idcard_handz['msg']];
		}
		//手持身份证反面
		$idcard_handf = upload('idcard_handf','auth',4);
		if($idcard_handf['code'] == 0){
			return ['code'=>0,'msg'=>$idcard_handf['msg']];
		}

		DB::beginTransaction();
		try {
			$user_auth = UserAuth::where('uid',request()->uid)->first();
			if($user_auth){
				UserAuth::where('uid',request()->uid)->update([
					'uid' => request()->uid,
					'name' => request()->name,
					'idcard' => request()->idcard,
					'idcard_headz' => $idcard_headz['data'],
					'idcard_headf' => $idcard_handf['data'],
					'idcard_handz' => $idcard_handz['data'],
					'idcard_handf' => $idcard_handf['data'],
					'state' => 3,
				]);
			}else{
				UserAuth::create([
					'uid' => request()->uid,
					'name' => request()->name,
					'idcard' => request()->idcard,
					'idcard_headz' => $idcard_headz['data'],
					'idcard_headf' => $idcard_handf['data'],
					'idcard_handz' => $idcard_handz['data'],
					'idcard_handf' => $idcard_handf['data'],
				]);
			}
			User::where('id',request()->uid)->update(['is_auth'=>4]);
			DB::commit();
			return ['code' => 1, 'msg' => retStrInfo(48)];
		} catch (Expectation $e) {
			DB::rollback();
			return ['code' => 0, 'msg' => retStrInfo(49)];
		}
	}
}